from flask import Flask, request, jsonify, abort
from flask import Flask
from admin_backend import update_user, get_all_users, get_single_user, renew_vip_service, query_user, \
    get_vip_packages, update_vip_package, delete_vip_package, create_admin, delete_admin, get_admins, update_admin, \
    delete_user, query_admin, get_image_by_id, get_images_by_admin
from config import Config
from models import db, User, UserCollect, CollectItem, UserAction, Admin, AdminAction
from datetime import datetime  # 必须导入datetime模块
import oss2

from admin_backend import admin_required, get_all_images, upload_image, delete_image, update_image

app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)  # 初始化数据库连接

auth = oss2.Auth('LTAI5tSSsZreQros8dcchrTe', 'dKoToq83nsV1xMTJN9VwIiryzKOkhg')

# 北京region的正确配置（根据控制台显示的实际region配置）
endpoint = "https://oss-cn-beijing.aliyuncs.com"
bucketName = "mjseed-code-image"
bucket = oss2.Bucket(auth, endpoint, bucketName)
def validate_login(username, password):
    """
    验证用户登录凭证
    :param username: 用户名或手机号
    :param password: 明文密码
    :return: User对象或None
    """
    user = User.query.filter(
        (User.user_name == username) |
        (User.phone_number == username)
    ).first()
    if user and user.check_password(password):
        return user
    return None

# ----------------- 路由定义 -----------------
@app.route('/login', methods=['POST','GET'])
def login():
    """
    用户登录接口
    Request JSON示例:
    {"username": "Leslie1", "password": "123123"}
    """
    data = request.json
    if not data or 'username' not in data or 'password' not in data:
        return jsonify({'error': '缺少必要参数'}), 400

    user = validate_login(data['username'], data['password'])
    if not user:
        return jsonify({'error': '用户名或密码错误'}), 401

    # 记录登录行为
    try:
        action = UserAction(
            user_id=user.user_id,
            action_type='login',
            create_at=datetime.now()
        )
        db.session.add(action)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': '系统错误'}), 500

    return jsonify({
        'user_id': user.user_id,
        'user_name': user.user_name,
        'membership_type': user.membership_type
    })

@app.route('/collect', methods=['POST', 'DELETE'])
def manage_collection():
    """
    收藏夹/项管理
    - POST创建: 需传collect_name或usercollect_id+image_id
    - DELETE删除: URL参数需传type=collect/item和id
    """
    # 验证用户身份
    user_id = request.headers.get('X-User-ID')
    if not user_id or not user_id.isdigit():
        return jsonify({'error': '未提供有效用户ID'}), 401

    # 处理创建请求
    if request.method == 'POST':
        data = request.json
        if not data:
            return jsonify({'error': '缺少请求体'}), 400

        try:
            # 创建收藏项
            if 'usercollect_id' in data:
                item = CollectItem(
                    usercollect_id=data['usercollect_id'],
                    image_id=data.get('image_id')
                )
                db.session.add(item)
            # 创建收藏夹
            else:
                if 'collect_name' not in data:
                    return jsonify({'error': '缺少收藏夹名称'}), 400
                folder = UserCollect(
                    user_id=user_id,
                    collect_name=data['collect_name']
                )
                db.session.add(folder)
            db.session.commit()
            return jsonify({'message': '操作成功'}), 201
        except Exception as e:
            db.session.rollback()
            return jsonify({'error': str(e)}), 500

    # 处理删除请求
    elif request.method == 'DELETE':
        target_id = request.args.get('id')
        target_type = request.args.get('type')

        if not target_id or not target_type:
            return jsonify({'error': '缺少必要参数'}), 400

        try:
            if target_type == 'collect':
                UserCollect.query.filter_by(usercollect_id=target_id).delete()
            elif target_type == 'item':
                CollectItem.query.filter_by(items_id=target_id).delete()
            else:
                return jsonify({'error': '无效的操作类型'}), 400
            db.session.commit()
            return jsonify({'message': '删除成功'}), 200
        except Exception as e:
            db.session.rollback()
            return jsonify({'error': str(e)}), 500

@app.route('/comment', methods=['POST'])
def post_comment():
    """
    发表评论接口
    Request JSON示例:
    {"image_id": "abc123", "comment": "这张图很棒！"}
    """
    user_id = request.headers.get('X-User-ID')
    if not user_id:
        return jsonify({'error': '未登录'}), 401

    data = request.json
    if not data or 'image_id' not in data or 'comment' not in data:
        return jsonify({'error': '缺少必要参数'}), 400

    try:
        # 记录评论行为
        action = UserAction(
            user_id=user_id,
            action_type='comment',
            image_id=data['image_id'],
            comment_context=data['comment'],
            create_at=datetime.now()
        )
        db.session.add(action)
        db.session.commit()
        return jsonify({'message': '评论成功'}), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500



# 管理员相关的路由

# 查看所有照片信息
@app.route('/admin/images', methods=['GET'])
@admin_required
def get_all_images_route():
    return get_all_images()


#查询全部oss照片的返回都是文件名
# @app.route('/admin/images/list', methods=['GET'])
# @admin_required
# def list_oss_files():
#     try:
#         result = bucket.list_objects()
#         files = [item.key for item in result.object_list]
#         return jsonify({'files': files}), 200
#     except Exception as e:
#         return jsonify({'error': str(e)}), 500


#   上传照片
@app.route('/admin/images/upload', methods=['POST'])
@admin_required
def upload_image_route():
    return upload_image()

#   删除照片
@app.route('/admin/images/<image_id>', methods=['DELETE'])
@admin_required
def delete_image_route(image_id):
    return delete_image(image_id)

#   更新照片
@app.route('/admin/images/<image_id>', methods=['PUT'])
@admin_required
def update_image_route(image_id):
    return update_image(image_id)

#   查询照片（id）
@app.route('/image/<int:image_id>', methods=['GET'])
def get_image(image_id):
    return get_image_by_id(image_id)

#   管理员查看自己发布的照片
@app.route('/admin/images/<int:admin_id>', methods=['GET'])
@admin_required
def handle_admin_images(admin_id):
    return get_images_by_admin(admin_id)




#   删除单个用户信息
app.add_url_rule('/admin/users/<int:user_id>', view_func=delete_user, methods=['DELETE'])

#   修改单个用户信息
app.add_url_rule('/admin/users/<int:user_id>', view_func=update_user, methods=['PUT'])

#   获取全部用户信息
app.add_url_rule('/admin/users', view_func=get_all_users, methods=['GET'])

#   查看单个用户信息
app.add_url_rule('/admin/users/<int:user_id>', view_func=get_single_user, methods=['GET'])

#   可以通过user_id、user_name、phone_number其中一个查询到单一用户信息
app.add_url_rule('/admin/query_user', view_func=query_user, methods=['GET'])

#   VIP充值续费
@app.route('/vip/renew', methods=['POST'])
def renew_vip():
    """
    VIP续费接口（支持套餐类型）
    Request JSON示例:
    {
        "user_id": 123,
        "payment_id": "PAY123",
        "package_type": "monthly",  # 新增参数
        "use_discount": false       # 是否使用折扣（预留字段）
    }
    """
    data = request.json
    required_fields = ['user_id', 'payment_id', 'package_type']
    if not all(field in data for field in required_fields):
        return jsonify({'error': '缺少必要参数'}), 400

    # 调用服务层
    result, status_code = renew_vip_service(
        user_id=data['user_id'],
        payment_id=data['payment_id'],
        package_type=data['package_type'],
        use_discount=data.get('use_discount', False)  # 预留折扣字段
    )
    return jsonify(result), status_code

# VIP套餐管理
app.add_url_rule('/admin/vip-packages', view_func=get_vip_packages, methods=['GET'])
app.add_url_rule('/admin/vip-packages', view_func=update_vip_package, methods=['POST', 'PUT'])
app.add_url_rule('/admin/vip-packages/<int:package_id>', view_func=delete_vip_package, methods=['DELETE'])


#对管理员的增删改查
app.add_url_rule('/admin/admins', view_func=create_admin, methods=['POST'])
app.add_url_rule('/admin/admins/<admin_id>', view_func=delete_admin, methods=['DELETE'])
app.add_url_rule('/admin/admins/<admin_id>', view_func=update_admin, methods=['PUT'])
app.add_url_rule('/admin/admins', view_func=get_admins, methods=['GET'])
app.add_url_rule('/admin/query', view_func=query_admin, methods=['GET'])





@app.route('/upload', methods=['POST'])
def upload_file():
    # 获取前端传来的文件
    file = request.files['file']
    if file:
        # 直接将文件上传到 OSS
        bucket.put_object(file.filename, file)
        return '上传成功'
    else:
        return '上传失败'

















if __name__ == '__main__':
    with app.app_context():
        # db.drop_all()  # 删除旧表（生产环境不要使用）
        db.create_all()  # 根据模型创建新表
    app.run(host='0.0.0.0', port=5000, debug=True)